package com.zhiban.project.controller;

import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;

import com.zhiban.project.domain.question.Question;
import com.zhiban.project.domain.question.QuestionContent;
import com.zhiban.project.util.ExcelUtil;
import com.zhiban.project.util.Object2Xml;

import dinamica.Config;
import dinamica.Db;
import dinamica.GenericTableManager;
import dinamica.Recordset;
import dinamica.RecordsetException;
import dinamica.xml.Document;

/**
 * 上传题目
 * 
 * @author lxp
 *
 */
public class UploadQuestionFile extends GenericTableManager {
	public UploadQuestionFile() {
	}

	public int service(Recordset inputParams) throws Throwable {
		HttpServletRequest request = this.getRequest();
		if (request.getAttribute("filename") == null) {
			throw new Throwable("文件不能为空!");
		}
		String filename = request.getAttribute("filename").toString();
		String filepath = request.getAttribute("filepath").toString();
		String  areaIdStr=request.getParameter("paramid");
		File tempFile = new File(filepath);
		if (!tempFile.exists())
			throw new Throwable("文件不能为空!");
		String localDir = getContext().getInitParameter("upload-dir");
		String currentTime = System.currentTimeMillis() + "";
		String ext = FilenameUtils.getExtension(filename);
		String newfilename = currentTime + "." + ext;
		File excelFile = new File(localDir, newfilename);
		FileUtils.copyFile(tempFile, excelFile);
		tempFile.delete();
		List<Map<String, String>> resultList = ExcelUtil.excelToList(excelFile
				.getAbsolutePath());
		excelFile.delete();
		Document doc = getConfig().getDocument();
		String sql = getSQL(getResource("insert.sql"), inputParams);
		Integer  areaId=0;
		if (StringUtils.isNotBlank(areaIdStr)) {
			areaId=Integer.parseInt(areaIdStr);
		}
		insertData(sql, resultList,areaId);
		int rc = 0;
		return rc;
	}

	private void insertData(String sql,
			List<Map<String, String>> questionMapList,Integer  areaId) {
		int index = 2;
		try {
			Db db = this.getDb();
			Recordset detail = new Recordset();
			detail.append("name", java.sql.Types.VARCHAR);
			detail.append("content", java.sql.Types.VARCHAR);
			detail.append("question_type_id", java.sql.Types.INTEGER);
			detail.append("duration", java.sql.Types.INTEGER);
			detail.append("answer", java.sql.Types.VARCHAR);
			detail.append("points", java.sql.Types.INTEGER);

			Set<String> questionSet = new HashSet<String>();
			for (Map<String, String> map : questionMapList) {
				detail.addNew();
				Question question = new Question();
				question.setName(map.get("题目").length() > 1000 ? map.get("题目")
						.substring(0, 1000) + "..." : map.get("题目"));
				if (StringUtils.isBlank(question.getName())) {
					continue;
				}
				if (map.get("类型").equals("单选题")
						|| map.get("类型").equals("单项选择题"))
					question.setQuestion_type_id(1);
				else if (map.get("类型").equals("多选题")
						|| map.get("类型").equals("多项选择题"))
					question.setQuestion_type_id(2);
				else if (map.get("类型").equals("判断题"))
					question.setQuestion_type_id(3);
				else if (map.get("类型").equals("填空题"))
					question.setQuestion_type_id(4);
				else if (map.get("类型").equals("问答题"))
					question.setQuestion_type_id(5);

				String value = question.getName() + "#"
						+ question.getQuestion_type_id();
				if (!questionSet.add(value)) {// 是否存在
					continue;
				}
				if (isExist(db, question,areaId)) {
					continue;
				}
				question.setAnalysis(map.get("解析"));
				question.setAnswer(map.get("答案"));
				if (question.getQuestion_type_id() == 3) {// 判断题
					if (map.get("答案").equals("对"))
						question.setAnswer("T");
					if (map.get("答案").equals("错"))
						question.setAnswer("F");
				}
				question.setPoints(map.get("分值").equals("") ? 0 : Float
						.parseFloat(map.get("分值")));
				QuestionContent qc = new QuestionContent();

				Iterator<String> it = map.keySet().iterator();
				List<String> keyStr = new ArrayList<String>();
				while (it.hasNext()) {
					String key = it.next();
					if (key.contains("选项"))
						keyStr.add(key.replace("选项", ""));
				}
				Collections.sort(keyStr);
				LinkedHashMap<String, String> choiceList = new LinkedHashMap<String, String>();
				for (int i = 0; i < keyStr.size(); i++) {
					if (!map.get("选项" + keyStr.get(i)).trim().equals(""))
						choiceList.put(keyStr.get(i),
								map.get("选项" + keyStr.get(i)));
				}

				if (question.getQuestion_type_id() == 1
						|| question.getQuestion_type_id() == 2)
					qc.setChoiceList(choiceList);
				qc.setTitle(map.get("题目"));
				String xmlStr = Object2Xml.toXml(qc);
				question.setContent(xmlStr);
				addQuestion(db, sql, detail, question);
				String cmd = getSQL(sql, detail);
				db.addBatchCommand(cmd);
				index++;
			}
			db.exec();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
			// throw new RuntimeException("第" + index + "行有错误，请检查！");
		} catch (Throwable e) {
			throw new RuntimeException(e.getMessage());
		}
	}

	private void addQuestion(Db db, String sql, Recordset detail,
			Question question) throws RecordsetException {
		detail.setValue("name", question.getName());
		detail.setValue("content", question.getContent());
		detail.setValue("question_type_id", question.getQuestion_type_id());
		detail.setValue("duration", question.getDuration());
		detail.setValue("answer", question.getAnswer());
		detail.setValue("points", question.getPoints());
	}

	/**
	 * 是否存在
	 * 
	 * @param db
	 * @param question
	 * @return
	 * @throws Throwable
	 */
	private boolean isExist(Db db, Question question,Integer  areaId) throws Throwable {
		String sql = "select count(1) num from  et_question where name ='"
				+ question.getName() + "' and question_type_id ="
				+ question.getQuestion_type_id();
		if (areaId>0) {
			sql=sql+" and area_id="+areaId;
		}
		Connection connection = db.getConnection();
		Statement statement = connection.createStatement();
		ResultSet resultSet = statement.executeQuery(sql);
		boolean exist = false;
		if (resultSet.next()) {
			Integer num = resultSet.getInt("num");
			if (num > 0) {
				exist = true;
			}
		}
		if (!statement.isClosed()) {
			statement.close();
		}
		return exist;
	}

	protected String formatRequestEncoding(String str) throws Throwable {
		Config _config = getConfig();
		String encoding = getContext().getInitParameter("request-encoding");
		if (encoding != null && encoding.trim().equals(""))
			encoding = null;
		if (_config.requestEncoding != null)
			return new String(str.getBytes("ISO8859-1"),
					_config.requestEncoding);
		if (encoding != null)
			return new String(str.getBytes("ISO8859-1"), encoding);
		else
			return str;
	}

	public static String getSpecificOutputPath(String root) {
		Calendar c = Calendar.getInstance(Locale.CHINA);
		return (new StringBuilder(String.valueOf(root))).append("/")
				.append(c.get(1)).append("/").append(c.get(2) + 1).append("/")
				.append(c.get(5)).append("/").append(c.get(11)).toString();
	}
}
